package com.stu.controller;

import com.stu.commons.ServerResponce;
import com.stu.commons.ServerResponse;
import com.stu.pojo.Coupon;
import com.stu.pojo.Mycoupon;
import com.stu.pojo.Users;
import com.stu.service.ICartService;
import com.stu.service.IMycouponService;
import com.stu.service.IProductService;
import com.stu.service.IUsersService;
import com.stu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;
    @Autowired
    private ICartService iCartService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IMycouponService iMycouponService;

    /* 注册 */
    @PostMapping("checkTelno")
    public Boolean checkTelno(String userTelno){
        System.out.println("userTelno:" + userTelno);

        List<Users> usersList = usersService.getAll();
        System.out.println(usersList);

        if(usersList != null){
            for(Users user: usersList){
                boolean nan = userTelno.equals(String.valueOf(user.getUserTelno()));
                System.out.println("nan:" + nan);

                if(nan)
                    return false; // 已注册
            }
        }
        return true; //未注册
    }

    //添加用户
    @PostMapping("save")
    public ServerResponse save(Users users, String userTelno, String userPwd){
        users.setUserNickname("用户" + UUID.randomUUID().toString().replace("-",""));
        users.setUserTelno(Long.valueOf(userTelno));
        users.setUserPwd(userPwd); //【加密！！！】
        return usersService.save(users);
    }

    /* 登录  */
    @PostMapping("login")
    public Object login(@RequestBody Users users, HttpServletRequest request, HttpServletResponse response){
        ServerResponce result = usersService.login(users);
        // 判断登录是否成功
        if (result.getCode() == 200) {
            // 如果登录成功，返回包含 userId 和 token 的 data
            return result;  // 直接返回封装了 userId 和 token 的数据
        } else {
            // 登录失败时返回失败信息
            return ServerResponce.fail("登录失败", null);
        }
    }

    @GetMapping("test1")
    public Map<String, Object> test1(HttpServletRequest request){
        //1.从头部获得token
        String token = request.getHeader("Authorization");
        String realToken = token.substring(7);

        if(token!=null) {
            //2.解析 token，获得登录用户的信息
            String userId = JwtUtil.getUserIdFromToken(realToken); // 使用新的 JwtUtil
            System.out.println("userId:" + userId);

            //3. 获取用户购物车数量
            Integer userCartProductCount = iCartService.getUserCartProductCount(Integer.valueOf(userId));

            //4.获得商品热数据
            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("userCartProductCount", userCartProductCount);
            return map;
        }
        return null;
    }

    //用户领取优惠券
    @GetMapping("usergetCoupon")
    public ServerResponce userGetCoupon(Coupon coupon, HttpServletRequest request){
        // 从token中获取用户的ID
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserIdFromToken(token); // 使用新的 JwtUtil
        Integer custId = Integer.valueOf(userId);

        // 获取优惠券的使用和到期时间
        LocalDateTime couponStartTime = coupon.getCouponStartTime();
        LocalDateTime couponEndTime = coupon.getCouponEndTime();

        // 创建Mycoupon
        Mycoupon mycoupon = new Mycoupon();
        mycoupon.setMycouponNumber(UUID.randomUUID().toString());
        mycoupon.setMycouponStatus(1);
        mycoupon.setMycouponGetTime(LocalDate.now());
        mycoupon.setUserId(custId);
        mycoupon.setCouponId(coupon.getCouponId());

        Integer insert = iMycouponService.insert(mycoupon);
        if(insert > 0){
            return ServerResponce.success("恭喜你领取优惠券成功", null);
        }
        return ServerResponce.fail("不好意思领取失败", null);
    }
}
